package com.nanhai.buddhist.college.module.collegebase.util;

import com.nanhai.buddhist.college.framework.common.exception.util.ServiceExceptionUtil;
import com.nanhai.buddhist.college.module.collegebase.enums.ErrorCodeConstants;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author AKai
 * @date 2022/9/27
 */
public class DateChangeUtil {
    /**
     * str  “yyyy-MM-dd”
     *
     * @return
     */
    public static Date stringToDateStart(String dateStr) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse;
        try {
            parse = sdf.parse(dateStr);
        } catch (Exception e) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.DATE_FORM_EXISTS);
        }
        return getBeginOfDay(parse);
    }

    public static Date stringToDateEnd(String dateStr) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse;
        try {
            parse = sdf.parse(dateStr);
        } catch (Exception e) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.DATE_FORM_EXISTS);
        }
        return getEndOfDay(parse);
    }


    public static Date getBeginOfDay(Date date){
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        return  now.getTime();
    }

    /**
     * 根据日期  获取结束时间
     * @param date
     * @return
     */
    public static Date getEndOfDay(Date date){
        Calendar now =Calendar.getInstance();
        now.setTime(getBeginOfDay(date));
        now.add(Calendar.DAY_OF_YEAR, 1);
        now.add(Calendar.MILLISECOND, -1);
        return  now.getTime();
    }

}
